package com.zhang.shiro;

import cn.hutool.json.JSONUtil;
import com.zhang.common.lang.Result;
import com.zhang.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtFilter extends AuthenticatingFilter {

    @Autowired
    JwtUtil jwtUtil;

    //白名单不进行shiro认证
    private static final String[] url_whiteList =
            {"/login","/blog/blogs","/blog/get/*","/user/getAvatar/*","/user/register","/comment/get/*","/file/get/*","/visit/*"};

    //用于shiro存放token信息
    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String authorization = request.getHeader("Authorization");
        if(authorization.isEmpty()){
            return null;
        }
        return new JwtToken(authorization);
    }

    //有Jwt后进行认证
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String authorization = request.getHeader("Authorization");

        if(isWhiteList(request)){   //白名单不交给shiro认证，直接访问
            return true;
        }

        if(authorization == null){    //jwt为空则不交给shiro进行处理，后面用注解拦截
            return true;
        }else {
            //先校验Jwt
            Claims claim = jwtUtil.getClaimByToken(authorization);
            if(claim == null || jwtUtil.tokenIsExpired(claim)){
                throw new ExpiredCredentialsException("token已失效，请重新登陆");
            }

            //执行登录
            return executeLogin(servletRequest,servletResponse);
        }
    }

    //重写父类登陆失败调用的方法
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {

        Throwable throwable = e.getCause()==null ? e : e.getCause();

        Result result = Result.fail(throwable.getMessage());
        String str = JSONUtil.toJsonStr(result);
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(str.getBytes("UTF-8"));
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }

        return false;
    }

    //用于解决前后端分离的跨域问题
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个OPTIONS请求，这里我们给OPTIONS请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(org.springframework.http.HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    //自定义的判断是否为白名单的方法
    private Boolean isWhiteList(HttpServletRequest request){
        Boolean is = false;
        String url = request.getRequestURI();
        String[] url_split = url.split("/");
        for(String white : url_whiteList){
            String[] white_split = white.split("/");
            if(url_split.length < white_split.length){
                is = false;
                continue;
            }
            for(int i=0;i<white_split.length;i++){
                if(white_split[i].equals("*")){
                    is = true;
                    break;
                }else  if(url_split[i].equals(white_split[i])){
                    is = true;
                }else {
                    is = false;
                    break;
                }
            }
            if(is){
                break;
            }
        }
        return is;
    }
}
